from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from model.cdn_node import CdnNode
from schema.cdn_node_schema import CdnNodeCreate, CdnNodeUpdate, CdnNodeOut
from typing import List
from route.user_api import get_current_user

router = APIRouter(
dependencies=[Depends(get_current_user)]  # 🔑 所有路由都需要认证
)

@router.post("/cdn_nodes", response_model=CdnNodeOut)
def create_cdn_node(node: CdnNodeCreate, db: Session = Depends(get_db)):
    db_node = db.query(CdnNode).filter(CdnNode.host == node.host).first()
    if db_node:
        raise HTTPException(status_code=400, detail="该节点已存在")

    new_node = CdnNode(**node.dict())
    db.add(new_node)
    db.commit()
    db.refresh(new_node)
    return new_node

@router.get("/cdn_nodes", response_model=List[CdnNodeOut])
def list_cdn_nodes(db: Session = Depends(get_db)):
    return db.query(CdnNode).all()

@router.get("/cdn_nodes/{node_id}", response_model=CdnNodeOut)
def get_cdn_node(node_id: int, db: Session = Depends(get_db)):
    node = db.query(CdnNode).filter(CdnNode.id == node_id).first()
    if not node:
        raise HTTPException(status_code=404, detail="节点不存在")
    return node

@router.put("/cdn_nodes/{node_id}", response_model=CdnNodeOut)
def update_cdn_node(node_id: int, node_update: CdnNodeUpdate, db: Session = Depends(get_db)):
    node = db.query(CdnNode).filter(CdnNode.id == node_id).first()
    if not node:
        raise HTTPException(status_code=404, detail="节点不存在")

    for key, value in node_update.dict(exclude_unset=True).items():
        setattr(node, key, value)

    db.commit()
    db.refresh(node)
    return node

@router.delete("/cdn_nodes/{node_id}")
def delete_cdn_node(node_id: int, db: Session = Depends(get_db)):
    node = db.query(CdnNode).filter(CdnNode.id == node_id).first()
    if not node:
        raise HTTPException(status_code=404, detail="节点不存在")

    db.delete(node)
    db.commit()
    return {"status": "success", "message": f"节点 {node_id} 已删除"}
